<?php
/** Copyright 2014 TinPhp Systems, Inc.
 * @author zhangxilian 2013-8-20
 * @package TinPhp
 */
class TinCookie
{
  /**
   * set cookie entry
   *
   * @key:      the name indicates the cookie entry
   * @value:    the value of the entry
   * @expired:  the time the cookie expires
   * @path:     the path in that the cookie will be reachable
   * @domain:   the domain in that the cookie will be valid
   * @secure:   indicates whether or not the cookie should be ONLY transmit by HTTPS protocol
   * @httponly: indicates whether or not the cookie should be ONLY transmit by HTTP protocol
   *
   * @return:   TRUE if cookie successfully set, otherwise return FALSE
   */
  public static function set($key, $value, $expired=0, $path='', $domain='', $secure=FALSE, $httponly=FALSE)
  {
    //$value = serialize($value);  
		$time = time() + (int)$expired;	

    return setcookie($key, $value, $time, $path, $domain, $secure);
  }

  /**
   * remove entry/entries indicates by @keys
   *
   * return TRUE if every entry/entries is successfully removed from cookie
   */
  public static function remove($keys)
  {
    if (!$keys) {
      return FALSE;
    }

    $keyarr = array();
    if (!is_array($keys)) {
      if (!is_string($keys)) {
        return FALSE;
      } else {
        $keyarr[] = $keys;
      }
    } else {
      $keyarr = $keys;
    }
 
    foreach ($keyarr as $key) {
      if (!TinCookie::exists($key)) {
        return FALSE;
      }

      unset($_COOKIE[$key]);
      setcookie($key);
    }
    return TRUE;
  }

  /**
   * get value of the entry identified by @key from cookie
   *
   * return NULL if the entry is not exist
   */
  public static function get($key)
	{
		if (!TinCookie::exists($key)) {
			return NULL;
		}

    $value = NULL;
    if (get_magic_quotes_gpc()) {
      $value = stripslashes($_COOKIE[$key]);
    } else {
      $value = $_COOKIE[$key];
    }

    if (!$value) {
      return NULL;
    } else {
      return $value;
      /*
      $unse = @unserialize($value);
      return ($unse) ? $unse : NULL;
      */
    }
	}

  /**
   * check the entry identified by @key is exist
   */
  public static function exists($key)
  {
    return isset($_COOKIE[$key]);
  }
}
